<template>
    <div class="flex_row_center">
        <input type="file" @change="onSelect" ref="fileInput" class="file_input" :accept="props.accpet"/>
        <el-button @click="onClick" type="primary">{{ props.name }}</el-button>
        <label class="ml5">{{ ctx.name }}</label>
    </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';

const fileInput = ref<HTMLInputElement | null>(null);

interface Props {
    name: string,
    accpet: string,
}

const props = defineProps<Props>();

interface Ctx {
    name: string,
}

const ctx = reactive<Ctx>({
    name: ''
});

const emit = defineEmits(['file-select']);

function onClick() {
    fileInput.value?.click();
    emit('file-select', null);
    ctx.name = "";
}

function onSelect(e: Event) {
    const target = e.target as HTMLInputElement;
    const files = target.files;
    if ((files == null) || (files.length == 0)) {
        return;
    }
    const file = files.item(0);
    if (file == null) {
        return;
    }
    ctx.name = file.name;
    emit('file-select', file);
}

</script>

<style scoped>

.file_input {
    display: none;
}

</style>
